package cn.timeapi.Applet.Mall.CatSquare.service.impl;

import cn.timeapi.Applet.Mall.CatSquare.service.ILogin;
import cn.timeapi.Applet.Mall.CatSquare.common.HttpClientUtil;
import cn.timeapi.Applet.Mall.CatSquare.common.JsonUtils;
import cn.timeapi.Applet.Mall.CatSquare.common.ServerResponse;
import cn.timeapi.Applet.Mall.CatSquare.config.WxConfig;
import cn.timeapi.Applet.Mall.CatSquare.model.WXSessionModel;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 登入服务实现
 * @author: Vincent Vic
 * @email: vincent-vic@qq.com
 * @time: 2020/9/28 20:33
 */

@Service("iLogin")
public class LoginImpl implements ILogin {

    @Override
    public ServerResponse<WXSessionModel> wxLogin(String code) {

//		https://api.weixin.qq.com/sns/jscode2session?
//				appid=APPID&
//				secret=SECRET&
//				js_code=JSCODE&
//				grant_type=authorization_code

        Map<String, String> param = new HashMap<>();
        //appid
        param.put("appid", WxConfig.appid);
        //密钥
        param.put("secret", WxConfig.secret);
        param.put("js_code", code);
        param.put("grant_type", WxConfig.grant_type);

        String wxResult = HttpClientUtil.doGet(WxConfig.url, param);
        System.out.println(wxResult);


		WXSessionModel model = JsonUtils.jsonToPojo(wxResult, WXSessionModel.class);
        System.out.println(model);

        if ( model.getErrcode() != 0){
            return ServerResponse.error(model);
        }

//
//		// 存入session到redis
//		redis.set("user-redis-session:" + model.getOpenid(),
//							model.getSession_key(),
//							1000 * 60 * 30);
        return  ServerResponse.success(model);
    }
}
